/**
 * 读取执行id
 */
var read = function(id) {
    if(window.localStorage) {
        return window.localStorage["mine_async_" + id];
    }
    return undefined;
};

/**
 * 请求token
 * @param appId
 * @param doneFunc
 * @param successFunc
 */
var requestToken = function(appId, doneFunc, successFunc) {
    $.ajax({
        url: contextPath + "/api/ai/mine/webapi/gen-token",
        type: 'POST',
        data: {id: appId},
        success: function(result) {
            doneFunc(result);
            if(result.success) {
                successFunc(result.data);
            } else {
                $("<div/>").alert({msg : "获取API访问token失败", height : 180});
            }
        }
    })
};

/**
 * 存储执行id
 */
var store = function(id, eid) {
    if(window.localStorage) {
        window.localStorage["mine_async_" + id] = eid;
    }
};

/**
 * 绑定异步服务测试页面事件
 * @param rowData
 */
var bindAsyncEvent = function(rowData) {
    var that = this.asyncDialog;
    var board = that.find('#mine-flow-json-area');
    var showJson = function (text, append) {
        if (append) {
            var value = board.val();
            board.val(value + "\n" + text);
        } else {
            board.val(text);
        }
    };
    var _eid = read(rowData.id);
    if (_eid) {
        that.find('input[name="eid"]').val(_eid);

        //停止
        that.find('.exebtn').text("停止");
        that.find('.exebtn').removeClass("execute-btn");
        that.find('.exebtn').addClass("stop-btn");
        updateAsyncState(rowData);
    } else {

    }
    that.find('.exebtn').click(function () {
        if(that.find('.exebtn').text() === "执行") {

            that.find(".tempo-step__head").removeClass("is-finish");
            that.find(".tempo-step__head").addClass("is-wait");
            that.find(".tempo-step__title").removeClass("is-finish");
            that.find(".tempo-step__title").addClass("is-wait");
            that.find(".tempo-step__line-inner").css("border-width", "1px");
            that.find(".tempo-step__line-inner").css("width", "100%");

            var serviceinfo = getServiceInfo();
            var eid = that.find('input[name="eid"]').val();
            if (eid) {
                //任务已经执行
                $("<div/>").alert({
                    msg: TempoUtils.locale("mine.renwuyijingzhixing"),
                    width: '500px'
                });
                return;
            }
            if (serviceinfo) {
                //停止
                that.find('.exebtn').text("停止");
                that.find('.exebtn').removeClass("execute-btn");
                that.find('.exebtn').addClass("stop-btn");
                var ptable = that.find('#ptable tbody tr');
                var params = {};
                if (ptable && ptable.size() > 0) {
                    for(var i = 0; i < ptable.length; i++) {
                        var pname = $(ptable[i]).find('span[name="pname"]').text();
                        var pvalue = $(ptable[i]).find('select[type="pvalue"]').selectmenu("getValue");
                        if(typeof pname === "undefined") {
                            continue;
                        }
                        if (pname && pname.trim().length > 0 && pvalue && pvalue.trim().length > 0) {
                            params[pname] = pvalue;
                        }
                    }
                }
                var record = TempoUtils.clone(params);
                delete record.requestId;
                var str = JSON.stringify(record, '', 2);
                showJson(TempoUtils.locale("mine.qingqiushujugeshi") + "\n" + str);
                var process = $("<div/>").tempoprogressbar();
                requestToken(serviceinfo.skCode, function (result) {
                    if (!result.success) {
                        process.tempoprogressbar("destroy");
                    }
                }, function (token) {
                    $.ajax({
                        url: contextPath + "/webapi/ai/model/async/execute/" + serviceinfo.url,
                        data: params,
                        headers: {
                            "App-Key": serviceinfo.clientCode,
                            "App-Token": token
                        },
                        success: function (res) {
                            var result = res.data;
                            var str = JSON.stringify(result, '', 2);
                            showJson(TempoUtils.locale("mine.fanhuishujugeshi") + "\n" + str, true);
                            process.tempoprogressbar("destroy");

                            if (result && result.eid) {
                                that.find('input[name="eid"]').val(result.eid);
                                updateAsyncState(rowData);
                                store(rowData.id, result.eid);
                            } else {
                                that.find('.exebtn').text("执行");
                                that.find('.exebtn').addClass("execute-btn");
                                that.find('.exebtn').removeClass("stop-btn");
                                $("<div/>").alert({
                                    msg: res.message,
                                    width: '500px'
                                });
                            }
                        }
                    })
                });
            } else {
                $("<div/>").alert({
                    msg: TempoUtils.locale("mine.fuwudizhikehuduanbiaomheshouquanma"),
                    width: '500px'
                });
            }
            return false;
        } else {
            killService(that, rowData, showJson);
        }

    });
};

/**
 * 杀死服务
 * @param that
 */
var killService = function (that, rowData, showJson) {
    var serviceinfo = getServiceInfo();
    if(serviceinfo){
        var eid = that.find('input[name="eid"]').val();
        if(!eid || eid.trim().length == 0){
            $("<div/>").alert({
                msg : TempoUtils.locale("mine.zhixingidweikong"),
                width : '250px'
            });
        }else{
            var data = {
                eid : eid
            };
            var str = JSON.stringify(data, '', 2);
            showJson(TempoUtils.locale("mine.qingqiushujugeshi")+"\n" + str);
            var process = $("<div/>").tempoprogressbar();
            requestToken(serviceinfo.skCode , function(result) {
                if(!result.success) {
                    process.tempoprogressbar("destroy");
                }
            },function(token) {
                $.ajax({
                    url : contextPath + "/webapi/ai/model/async/kill/" + serviceinfo.url,
                    data : {
                        eid : eid
                    },
                    headers: {
                        "App-Key": serviceinfo.clientCode,
                        "App-Token": token
                    },
                    success : function(res){
                        var result = res.data || {};
                        var str = JSON.stringify(result, '', 2);
                        showJson(TempoUtils.locale("mine.fanhuishujugeshi")+"\n" + str, true);
                        process.tempoprogressbar("destroy");
                        if(result) {
                            that.find(".tempo-step__head").removeClass("is-finish");
                            that.find(".tempo-step__head").addClass("is-wait");
                            that.find(".tempo-step__title").removeClass("is-finish");
                            that.find(".tempo-step__title").addClass("is-wait");
                            that.find(".tempo-step__line-inner").css("border-width", "1px");
                            that.find(".tempo-step__line-inner").css("width", "100%");
                        }
                        if(res.success) {
                            clearState(rowData.id);
                        }
                        $('#mine-opt-service-grid').jqGrid().trigger('reloadGrid');

                        that.find('.exebtn').text("执行");
                        that.find('.exebtn').addClass("execute-btn");
                        that.find('.exebtn').removeClass("stop-btn");
                    }
                })
            });
        }
    }else{
        $("<div/>").alert({
            msg : TempoUtils.locale("mine.fuwudizhikehuduanbiaomheshouquanma"),
            width : '500px'
        });
    }
    return false;
};

/**
 * 获取服务信息
 * @returns {null|{skCode: *, clientCode: *, url: *}}
 */
var getServiceInfo = function(){
    var that = this.asyncDialog;
    var url = that.find('input[name="async-test-data-url"]').val();
    var clientCode = that.find('input[name="async-test-data-clientcode"]').val();
    var skCode = that.find('input[name="async-test-data-skcode"]').val();

    if(!url || url.trim().length == 0){
        return null;
    }
    if(!clientCode || clientCode.trim().length == 0){
        return null;
    }
    if(!skCode || skCode.trim().length == 0){
        return null;
    }
    url = url.substr(url.lastIndexOf('/')+1)
    return {
        url : url,
        clientCode:clientCode,
        skCode:skCode
    }
};

/**
 * 清除状态
 */
var clearState = function(id) {
    var that = this.asyncDialog;
    that.find('input[name="eid"]').val('');
    if(window.localStorage) {
        if(window.localStorage["mine_async_" + id]) {
            delete window.localStorage["mine_async_" + id];
        }
    }
    setTimeout(function() {
        $('#mine-opt-service-grid').jqGrid().trigger('reloadGrid');
    }, 2000);
};

var stack = ['SUBMITING', 'SUBMITTED', 'STARTING', 'RUNNING'];
/**
 * 更新同步服务状态
 * @param rowData
 */
var updateAsyncState = function(rowData) {
    var that = this.asyncDialog;
    if(!that) return ;
    var serviceinfo = getServiceInfo();

    if(serviceinfo){
        var eid = that.find('input[name="eid"]').val();
        if(!eid || eid.trim().length == 0){
            console.error("eid is null");
            return ;
        }else{
            requestToken(serviceinfo.skCode , $.noop,function(token) {
                $.ajax({
                    url : contextPath + "/webapi/ai/model/async/status/" + serviceinfo.url,
                    data : {
                        eid : eid
                    },
                    headers: {
                        "App-Key": serviceinfo.clientCode,
                        "App-Token": token
                    },
                    success : function(res){
                        var result = res.data;
                        if(result) {
                            var lightDiv = function (div, fallback) {
                                div.find(".tempo-step__head").removeClass("is-wait");
                                div.find(".tempo-step__head").addClass("is-finish");
                                div.find(".tempo-step__title").removeClass("is-wait");
                                div.find(".tempo-step__title").addClass("is-finish");
                                if(fallback) fallback.call(div);
                            };
                            if(result.status && stack.indexOf(result.status) > -1) {
                                if("SUBMITING" === result.status || "SUBMITTED" === result.status) {
                                    //点亮提交完毕等待执行
                                    lightDiv(that.find("div[currentIndex=1]"), function () {
                                        this.find(".tempo-step__line-inner").css("width", "0px");


                                    });
                                }
                                if("RUNNING" === result.status) {
                                    //点亮正在执行
                                    lightDiv(that.find("div[currentIndex=1]"), function () {
                                        this.find(".tempo-step__line-inner").css("border-width", "1px");
                                        this.find(".tempo-step__line-inner").css("width", "100%");
                                    });
                                    lightDiv(that.find("div[currentIndex=2]"), function () {
                                        this.find(".tempo-step__line-inner").css("width", "0px");
                                    });
                                }
                                setTimeout(function(){
                                    updateAsyncState(rowData);
                                }, 2000);
                            } else {
                                if("FINISHED" === result.status || "FAILED" === result.status || "KILLED" === result.status) {
                                    lightDiv(that.find("div[currentIndex=1]"), function () {
                                        this.find(".tempo-step__line-inner").css("border-width", "1px");
                                        this.find(".tempo-step__line-inner").css("width", "100%");
                                    });
                                    lightDiv(that.find("div[currentIndex=2]"), function () {
                                        this.find(".tempo-step__line-inner").css("border-width", "1px");
                                        this.find(".tempo-step__line-inner").css("width", "100%");
                                    });
                                    lightDiv(that.find("div[currentIndex=3]"), function () {
                                        this.find(".tempo-step__line-inner").css("width", "0px");
                                    });
                                }
                                clearState(rowData.id);
                                that.find('.exebtn').text("执行");
                                that.find('.exebtn').addClass("execute-btn");
                                that.find('.exebtn').removeClass("stop-btn");
                            }
                        }
                    }
                })
            });
        }
    }
};

/**
 * 创建流程参数input
 * @param paramGrid
 * @param paramValueIndex
 * @param paramTypeIndex
 * @param nodeTypeValue
 * @param test
 */
var createFlowParamValueInput = function (paramGrid, paramValueIndex, paramTypeIndex, nodeTypeValue, test) {
    var trs = paramGrid.find("tr");
    for(var i = 1; i < trs.length; i++) {
        var paramValueTd = $(trs[i]).find("td:nth-child("+ paramValueIndex +")");
        var paramValue = paramValueTd.text().trim();
        paramValueTd.empty();

        var paramValueSelect = $('<select type="pvalue"/>').val(paramValue).appendTo(paramValueTd);
        var pss = [];

        var paramTypeTd = $(trs[i]).find("td:nth-child("+ paramTypeIndex +")");
        var type = paramTypeTd.text();

        var nodeTypeTd = $(trs[i]).find("td:nth-child("+ nodeTypeValue +")");
        var nodeType = nodeTypeTd.text();

        if(type == 'datasource'){
            var loadDatasource = function(data) {
                for(var j = 0; j < data.length;j++){
                    var dataItem = data[j];
                    // 屏蔽模型数据源、presto数据源、impala数据源
                    if (nodeType == 'readrdbms') {
                        if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1) {
                            continue;
                        }
                    }
                    if (nodeType == 'writerdbms') {
                        if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1 || (dataItem.purpose && dataItem.purpose != "1")) {
                            continue;
                        }
                    }

                    if (nodeType == 'readhive') {
                        if (dataItem.type != 'hive') {
                            continue;
                        }
                    }
                    if(nodeType == 'writehive'){
                        if('hive' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")){
                            continue;
                        }
                    }
                    if (nodeType == "readinfluxdb") {
                        if (!(dataItem.type == "influxdb" || dataItem.type == "influxdb2")) {
                            continue;
                        }
                    }
                    if( nodeType == "readiotdb"){
                        if (dataItem.type != 'iotdb') {
                            continue;
                        }
                    }
                    if( nodeType == "writeiotdb"){
                        //不是iotdb  或者不能写入
                        if ('iotdb' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")) {
                            continue;
                        }
                    }

                    pss.push('<option value="' + dataItem.code + '">' + dataItem.name + '</option>')
                }
                var html = pss.join('');
                paramValueSelect.html(html);

                var pVSWidth = "80%";
                if(test) {
                    pVSWidth = "200px";
                }

                paramValueSelect.selectmenu({
                    editable : false,
                    width : pVSWidth
                }).selectmenu('setValue', $(trs[i]).find("td:nth-child(7)").text()).selectmenu('refresh');
            };
            if(dataSourceCache['datasource']) {
                loadDatasource(dataSourceCache['datasource']);
            } else {
                $.ajax({
                    url:contextPath + '/api/ai/node/io/list-datasources',
                    type:'post',
                    data: {
                        isFilterWritable:true //是否过滤可写
                    },
                    async: false,
                    success:function(data) {
                        if(data.success) {
                            dataSourceCache['datasource'] = data.data;
                            loadDatasource(dataSourceCache['datasource']);
                        } else {
                            console.error("数据源加载失败");
                        }
                    }
                });
            }
        } else {
            var items = TempoMineUtils.getConstFlowParams();
            if(items){
                for(name in items){
                    pss.push('<option value="' + name + '">' + items[name] + '</option>')
                }
            }

            var html = pss.join('');
            paramValueSelect.html(html);
            var pVSWidth = "80%";
            if(test) {
                pVSWidth = "200px";
            }
            paramValueSelect.selectmenu({
                editable : true,
                width : pVSWidth,
            }).selectmenu('setValue', paramValue);
        }
    }
};

/***
 * 异步服务测试页面
 * @param rowData
 */
var testAsyncFlow = function(rowData) {
    var that = this;
    $.post(contextPath + '/api/ai/mine/async/testdialog', rowData, function(res) {
        var testDialog = $(res);
        that.asyncDialog = testDialog.appendTo('body');
        that.asyncDialog.dialog({
            width : 720,
            height: 570,
            autoOpen : true,
            title: "服务测试-" + TempoMineUtils.decodeHTML(rowData.name),
            modal:true,
            resizable: false,
            close:function(){
                that.asyncDialog.dialog("destroy");
                that.asyncDialog = null;
                if(!rowData.ignore) {
                    $('#mine-opt-service-grid').jqGrid().trigger('reloadGrid');
                }
                $("#async-test-dialog").remove();
            },
            open : function() {
                var form = $(this).find("form");
                TempoUtils.parserUi(form, {});
                //将其他的授权码添加进来，组成下拉框供选择
                var tokens = $(this).find('span.token').map(function() {
                    var clientCode = $(this).attr('clientCode');
                    var skCode = $(this).attr('skCode');
                    return {clientCode: clientCode, skCode: skCode,callName:$(this).attr('callName')};
                }).get();
                var skinput = form.find('input[name=async-test-data-skcode]');
                var callinput = form.find('span[name=async-test-data-callname]');
                var select = form.find('#selectCode');
                var tkObject = {};
                tokens.forEach(function(e) {
                    $('<option />').attr('value', e.clientCode).text(e.clientCode).appendTo(select);
                    tkObject[e.clientCode] = [e.skCode,e.callName];
                });
                select.selectmenu({
                    width: 270,
                    select: function(e, ui) {
                        skinput.val(tkObject[ui.item.value][0]);
                        callinput.text(tkObject[ui.item.value][1]);
                        callinput.attr("title", tkObject[ui.item.value][1]);
                        //原代码中往后台传参的组件
                        form.find('[name=async-test-data-clientcode]').val(ui.item.value);
                    }
                }).selectmenu('setValue', select.prev().val()).selectmenu('refresh');
                form.find('[name=serviceId]').text(rowData.id);
                var tempoBaseUrl = location.protocol + "//" + location.host + contextPath + "/webapi/ai/model/async/execute/" + rowData.id ;
                form.find('[name=async-test-data-url]').val(tempoBaseUrl);

                //初始化流程参数
                createFlowParamValueInput(that.asyncDialog.find("#ptable"), 4, 5, 6, true);
                bindAsyncEvent(rowData);
            },
            buttons:[{
                text: TempoUtils.locale("mine.guanbi"),
                click:function(){
                    that.asyncDialog.dialog("destroy");
                    $("#async-test-dialog").remove();
                }
            }]
        });
        //初始化title
        var titleDiv = that.asyncDialog.parent().find(".ui-dialog-titlebar");
        titleDiv.find(".ui-dialog-title").addClass("async-test-dialog-title");
        titleDiv.find(".ui-dialog-title").css("display", "block");
        $("<span class='tempo-tag tempo-tag--success' style='margin-left: 10px'>异步</span>").appendTo(titleDiv.find(".async-test-dialog-title"));
        //初始化取消按钮
        that.asyncDialog.parent().find(".ui-dialog-buttonset").find("button").addClass("async-test-dialog-cancle-btn");
    })
};


var bindSyncTest = function(rowData,skInfo){
    var that = this.syncDialog;
    var form = that.find("form");
    TempoUtils.parserUi(form, {});

    var tokens = that.find('span.token').map(function() {
        var clientCode = $(this).attr('clientCode');
        var skCode = $(this).attr('skCode');
        return {clientCode: clientCode, skCode: skCode,callName:$(this).attr('callName')};
    }).get();
    //隐藏证书key
    var ccinput = $('input[name=sync-test-data-clientcode]').hide();
    //获取证书授权码
    var skinput = $('input[name=sync-test-data-skcode]');
    //获取证书名称
    var callinput = $('span[name=sync-test-data-callname]');
    var cvalue = ccinput.val();
    var select = form.find('#selectCode');
    var tkObject = {};
    tokens.forEach(function(e) {
        $('<option />').attr('value', e.clientCode).text(e.clientCode).appendTo(select);
        tkObject[e.clientCode] = [e.skCode,e.callName];
    });
    select.selectmenu({
        width: 270,
        select: function(e, ui) {
            ccinput.val(ui.item.value);
            skinput.val(tkObject[ui.item.value][0]);
            callinput.text(tkObject[ui.item.value][1])
            callinput.attr("title", tkObject[ui.item.value][1]);
        }
    }).selectmenu('setValue', cvalue).selectmenu('refresh');

    that.find('#mine-flow-btn-test').button({
        useRadius : false,
        label : TempoUtils.locale("mine.test"),
        click : function() {
            $.post({
                async: false,
                url: contextPath + '/api/ai/app/model/status/' + rowData.id,
                success: function (rp) {
                    //更新同步服务当前状态
                    rowData.launchState = rp.data;
                }
            });
            if(rowData.launchState == 'STARTING') {
                $("<div/>").alert({msg : TempoUtils.locale("mine.service-starting"), height : 180});
                return ;
            } else if(!rowData.launchState || rowData.launchState == 'NONE') {
                if(!rowData.ignore) {
                    $("<div/>").confirm({
                        title: TempoUtils.locale("mine.prompt"),
                        msg: TempoUtils.locale("mine.start-service-yes-no"),
                        ok: function() {
                            operateOfSetting.apply(that, [null, {rowData: rowData}]);
                        }
                    })
                } else {
                    $("<div/>").alert({msg : TempoUtils.locale("mine.qingkaiqifuwu"), height : 180});
                }
                return ;
            }
            if(!form.formValidate()) {
                $("<div/>").alert({msg : TempoUtils.locale("mine.serviceparamisnotnull"), height : 180});
                return ;
            }
            var record = TempoUtils.getRecord(form);
            record['mine-flow-json-area'] = undefined;
            var data = TempoUtils.clone(record);
            var json = {};
            delete data['sync-test-data-clientcode'];
            delete data['sync-test-data-skcode'];
            delete data['sync-test-data-name'];
            delete data['serviceAddress'];

            json['rows'] = [data];

            var str = JSON.stringify(json, null, 2);
            that.find('#mine-flow-json-area').val(str);
            var process = $("<div/>").tempoprogressbar();

            var address = form.find('input[name=serviceAddress]').val();
            var search = window.location.search;
            // 反序列化传入的参数
            var params = TempoUtils.unSerialize(search);
            // 使用tomcat中转访问同步服务
            //fix:67691 当同步输入参数包含address时，测试失败
            //record.address = address;
            $.post(contextPath + '/api/ai/mine/sync/example/' + rowData.id,
                record,
                function(d) {
                    process.tempoprogressbar("destroy");
                    var info = [];
                    var board = that.find('.mine-flow-test-result');
                    if(d.status == "FINISHED") {
                        info.push(TempoUtils.locale("mine.ceshizhuangtaichenggong"));
                        info.push(TempoUtils.locale("mine.ceshijieguo"));
                        for(var r in d.result) {
                            info.push("    " + TempoUtils.locale("mine.tongbushuchu") + d.result[r].name);
                            for(var num in d.result[r].rows) {
                                var row = d.result[r].rows[num];
                                var count = d.result[r].count;
                                var columns = d.result[r].columns;
                                for(var i in columns) {
                                    var col = columns[i]
                                    info.push('      "' + col.name + '"："' + row[col.name] + '"');
                                }
                                info.push("    " + TempoUtils.locale("mine.testCount") + "：" + count);
                            }
                        }
                        info.push(TempoUtils.locale("mine.ceshicuowudaima") + d.code);
                    } else {
                        info.push(TempoUtils.locale("mine.ceshizhuangtaishibai"));
                        info.push(TempoUtils.locale("mine.ceshicuowudaima") + d.code);
                        info.push(TempoUtils.locale("mine.cuowuxinxi"));
                        info.push(d.error);
                    };
                    board.val(info.join('\n'));
                });
        }
    });
};

var bindGrayTest = function(rowData,skInfo){
    var that = this.grayDialog;
    var form = that.find("form");
    TempoUtils.parserUi(form, {});
    var message = "";

    var tokens = that.find('span.token').map(function() {
        var clientCode = $(this).attr('clientCode');
        var skCode = $(this).attr('skCode');
        return {clientCode: clientCode, skCode: skCode,callName:$(this).attr('callName')};
    }).get();
    //隐藏证书key
    var ccinput = $('input[name=gray-test-data-clientcode]').hide();
    //获取证书授权码
    var skinput = $('input[name=gray-test-data-skcode]');
    //获取证书名称
    var callinput = $('span[name=gray-test-data-callname]');
    var cvalue = ccinput.val();
    var select = form.find('#selectCode');
    var tkObject = {};
    tokens.forEach(function(e) {
        $('<option />').attr('value', e.clientCode).text(e.callName).appendTo(select);
         tkObject[e.clientCode] = [e.skCode,e.callName];
    });
    select.selectmenu({
        width: 224,
        select: function(e, ui) {
            ccinput.val(ui.item.value);
            skinput.val(tkObject[ui.item.value][0]);
            callinput.text(tkObject[ui.item.value][1])
            callinput.attr("title", tkObject[ui.item.value][1]);
        }
    }).selectmenu('setValue', cvalue).selectmenu('refresh');

    that.find('#mine-gray-btn-test').button({
        useRadius : false,
        label : TempoUtils.locale("mine.test"),
        click : function() {
            $.post({
                async: false,
                url: contextPath + '/api/ai/mine/gray/status/' + rowData.id,
                success: function (rp) {
                    //更新灰度服务当前状态
                    if(rp.data != null){
                        rowData.status = rp.data.status;
                        message = rp.message;
                    }
                }
            });
            if(rowData.status === "0") {
                $("<div/>").alert({msg : message, height : 180});
                return ;
            }
            var launchState = true;
            $.post({
                async: false,
                url: contextPath + '/api/ai/mine/gray/gray-sync-status/' + rowData.id,
                success: function (rp) {
                    launchState = rp.success;
                    message = rp.message;
                }
            });
            if(!launchState){
                $("<div/>").alert({msg : message, height : 180});
                return ;
            }
            if(!form.formValidate()) {
                $("<div/>").alert({msg : TempoUtils.locale("mine.serviceparamisnotnull"), height : 180});
                return ;
            }

            var record = TempoUtils.getRecord(form);
            record['mine-flow-json-area'] = undefined;
            var data = TempoUtils.clone(record);
            var json = {};
            delete data['gray-test-data-clientcode'];
            delete data['gray-test-data-skcode'];
            delete data['gray-test-data-name'];
            delete data['serviceAddress'];

            json['rows'] = [data];

            var str = JSON.stringify(json, null, 2);
            that.find('#mine-flow-json-area').val(str);
            var process = $("<div/>").tempoprogressbar();

            var address = form.find('input[name=serviceAddress]').val();
            var search = window.location.search;
            // 反序列化传入的参数
            var params = TempoUtils.unSerialize(search);

            // 使用tomcat中转访问同步服务
            record.address = address;
            delete rowData.flowid;
            delete rowData.ignore;
            delete rowData.launchState;
            $.post(contextPath + '/api/ai/mine/gray/example',{
                    rowData:JSON.stringify(rowData),
                    param:JSON.stringify(record)
                },
                function(d) {
                    process.tempoprogressbar("destroy");
                    var info = [];
                    var board = that.find('.mine-flow-test-result');
                    if(d.status == "FINISHED") {
                        info.push(TempoUtils.locale("mine.ceshizhuangtaichenggong"));
                        info.push(TempoUtils.locale("mine.ceshijieguo"));
                        for(var r in d.result) {
                            info.push("    " + TempoUtils.locale("mine.tongbushuchu") + d.result[r].name);
                            for(var num in d.result[r].rows) {
                                var row = d.result[r].rows[num];
                                var count = d.result[r].count;
                                var columns = d.result[r].columns;
                                for(var i in columns) {
                                    var col = columns[i]
                                    info.push('      "' + col.name + '"："' + row[col.name] + '"');
                                }
                                info.push("    " + TempoUtils.locale("mine.testCount") + "：" + count);
                            }
                        }
                        info.push(TempoUtils.locale("mine.ceshicuowudaima") + d.code);
                    } else {
                        info.push(TempoUtils.locale("mine.ceshizhuangtaishibai"));
                        info.push(TempoUtils.locale("mine.ceshicuowudaima") + d.code);
                        info.push(TempoUtils.locale("mine.cuowuxinxi"));
                        info.push(d.error);
                    };
                    board.val(info.join('\n'));
                });
        }
    });
};

/**
 * 同步服务测试中内嵌的弹框
 */
var testSyncFlow = function(rowData,skInfo){
    //修改弹框内容
    var that = this;
    $.post(contextPath + '/api/ai/mine/sync/testdialog', rowData, function(res) {
        var testDialog = $(res);
        that.syncDialog = testDialog.appendTo('body');
        that.syncDialog.dialog({
            width : 720,
            height: 570,
            autoOpen : true,
            title: "服务测试-" + TempoMineUtils.decodeHTML(rowData.name),
            modal:true,
            resizable: false,
            close:function(){
                that.syncDialog.dialog("destroy");
                $("#sync-test-dialog").remove();
            },
            open : function() {
                bindSyncTest(rowData,skInfo);
            },
            buttons:[{
                text: TempoUtils.locale("mine.guanbi"),
                click:function(){
                    that.syncDialog.dialog("close");
                    $("#sync-test-dialog").remove();
                }
            }]
        });
        //初始化title
        var titleDiv = that.syncDialog.parent().find(".ui-dialog-titlebar");
        titleDiv.find(".ui-dialog-title").addClass("sync-test-dialog-title");
        titleDiv.find(".ui-dialog-title").css("display", "block");
        $("<span class='tempo-tag' style='margin-left: 10px'>同步</span>").appendTo(titleDiv.find(".sync-test-dialog-title"));
        //初始化取消按钮
        that.syncDialog.parent().find(".ui-dialog-buttonset").find("button").addClass("sync-test-dialog-cancle-btn");
    })

};

/**
 * 灰度服务测试中内嵌的弹框
 */
var testGray = function(rowData,skInfo){
    //修改弹框内容
    var that = this;
    $.post(contextPath + '/api/ai/mine/gray/testdialog', rowData, function(res) {
        var testDialog = $(res);
        that.grayDialog = testDialog.appendTo('body');
        that.grayDialog.dialog({
            width : 720,
            height: 570,
            autoOpen : true,
            title: "服务测试-" + TempoMineUtils.decodeHTML(rowData.name),
            modal:true,
            resizable: false,
            close:function(){
                that.grayDialog.dialog("destroy");
                $("#gray-test-dialog").remove();
            },
            open : function() {
                bindGrayTest(rowData,skInfo);
            },
            buttons:[{
                text: TempoUtils.locale("mine.guanbi"),
                click:function(){
                    that.grayDialog.dialog("close");
                    $("#gray-test-dialog").remove();
                }
            }]
        });
        //初始化title
        var titleDiv = that.grayDialog.parent().find(".ui-dialog-titlebar");
        titleDiv.find(".ui-dialog-title").addClass("gray-test-dialog-title");
        titleDiv.find(".ui-dialog-title").css("display", "block");
        $("<span class='tempo-tag' style='margin-left: 10px'>灰度</span>").appendTo(titleDiv.find(".gray-test-dialog-title"));
        //初始化取消按钮
        that.grayDialog.parent().find(".ui-dialog-buttonset").find("button").addClass("gray-test-dialog-cancle-btn");
    })

};


Eventbus.one('testASyncFlowMutual.mine', testAsyncFlow);
Eventbus.one('testSyncFlowMutual.mine', testSyncFlow);
Eventbus.one('testGrayMutual.mine', testGray);
Eventbus.one("ready.serviceTest", function () {
    return true;
}, this);


